const express = require('express')
const request = require('request-promise')

const app = express()

app.get('/price', async (req, res) => {
    let symbol = req.query.symbol
    if (!symbol) {
      return res.send({code: 1, data: null, message: '交易对不能为空'})
    }
    try {
      let price = await getPrice(symbol.toLowerCase())
      res.send({code: 0, data: {price: price}, message: '获取成功'})
    } catch (e) {
      res.send({code: 1, data: null, message: '获取价格失败'})
    }
  }
)

async function getPrice (symbol) {
  let res = await request({
    url: 'https://api.huobipro.com/market/history/kline',
    method: 'GET',
    qs: {
      period: '1day',
      size: 1,
      symbol: symbol
    },
    json: true
  })
  if (res.status === 'ok') {
    let kline = res.data[0]
    let {close} = kline
    return close
  } else {
    throw new Error('获取价格失败')
  }
}

// 捕获404
app.use((req, res, next) => {
  res.send({code: 404, data: null, message: '找不到你要的资源'})
})

const server = app.listen(3000, function () {
  const port = server.address().port

  console.log('Example app listening at http://localhost:%s', port)
})
